package com.docman.controller;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.docman.dao.DocumentDAO;
import com.docman.dao.UserDAO;
import com.docman.domainmodel.DocumentBean;
import com.docman.domainmodel.UserBean;


@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public LoginServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try {
			UserBean user = new UserBean();
		
			String userName = request.getParameter("username");
			String password = request.getParameter("pass");
			
			if(userName!=null && userName!="" ){
				user.setUserName(userName);
			}
			if(password!=null && password!="" ){
				try {
					MessageDigest md = MessageDigest.getInstance("SHA-256");
					 md.update(password.getBytes());
					 
				        byte byteData[] = md.digest();
				 
				        //convert the byte to hex format method 1
				        StringBuffer sb = new StringBuffer();
				        for (int i = 0; i < byteData.length; i++) {
				         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
				         password = sb.toString();
				        }
				} catch (NoSuchAlgorithmException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				user.setPassword(password);
			}
		
			if( user.getUserName()==null || user.getPassword()==null ){
				response.sendRedirect("index.jsp");
			}
			else {
				
				user = UserDAO.login(user);
				
				
			 	if (user.isValid())
		     	{
			       
		          HttpSession session = request.getSession();	    
		          session.setAttribute("currentSessionUser",user);		          
		          response.sendRedirect("index.jsp");      		
		     	}
			        
		     	else{
		     		request.setAttribute("error", "Kullanıcı kayıtlı değil veya hatalı şifre girişi.");
		     		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
					dispatcher.forward(request, response);
		    	}
			} 
			
		}
				
		catch (Throwable theException) 	    
		{
		     System.out.println(theException); 
		}
		
	}

}
